const express = require('express');
const cors = require('cors');
require('dotenv').config();

const { errorHandler, notFound } = require('./middleware/errorHandler');

// 导入路由
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/users');
const transactionRoutes = require('./routes/transactions');
const wineRoutes = require('./routes/wines');
const statsRoutes = require('./routes/stats');
const smsRoutes = require('./routes/sms');

const app = express();

// 中间件
app.use(cors({
  origin: process.env.CORS_ORIGIN || '*',
  credentials: true
}));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    success: true,
    message: '服务运行正常',
    timestamp: new Date().toISOString()
  });
});

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/transactions', transactionRoutes);
app.use('/api/wines', wineRoutes);
app.use('/api/stats', statsRoutes);
app.use('/api/sms', smsRoutes);

// 404处理
app.use(notFound);

// 错误处理
app.use(errorHandler);

module.exports = app;
